package br.com.merks.service;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.util.jpa.EntityManagerCreator;
import br.com.merks.model.Conf;
@Component
public class ConfServiceImpl implements ConfService {
	public static final Logger logger = Logger.getLogger(ConfServiceImpl.class);
	private EntityManager entityManager;
	private MailService mailService;
	public ConfServiceImpl(EntityManagerCreator emCreator, MailService mailService) {
		this.entityManager = emCreator.getInstance();
		this.mailService = mailService;
	}
	public Conf loadConf() {
		logger.debug("Loading conf object.");
		List<Conf> list = this.entityManager.createNamedQuery("conf.find").getResultList();
		if ((list==null)||(list.size()==0)) return null;
		return (Conf) list.get(0);
	}
	public Conf saveConf(Conf conf) {
		Conf dbConf = loadConf();
		if (dbConf!=null) {
			conf.setId(dbConf.getId());
			this.entityManager.getTransaction().begin();
			this.entityManager.merge(conf);
			this.entityManager.getTransaction().commit();
		} else {
			this.entityManager.getTransaction().begin();
			this.entityManager.persist(conf);
			this.entityManager.getTransaction().commit();
		}
		return conf;
	}

}
